export default {
	namespaced: true,
	
	state: () => ({
		// 购物车数据结构: []
		// 购物车中的某一商品结构：
				// goodsOne: {
				// 	id: '',
				// 	name: '',
				// 	price: '',
				// 	count: 0,
				// 	small_logo: '',
				// 	state: ''
				// },
		
		cart: JSON.parse(uni.getStorageSync('cart') || '[]'),
		checkAll: false
		
	}),
	
	mutations: {
		// 添加到购物车
		addToCart(state, val) {
			let state_goods = state.cart.find(x => x.goods_id === val.goods_id)
			state_goods ? state_goods.goods_count ++ : state.cart.push(val)
			
			this.commit('store_cart/saveToStorage')
			console.log('加入购物车成功！')
			console.log(state.cart)
		},
		
		// 持久化存储购物车数据
		saveToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		},
		
		// 修改 cart.goods_state
		updateState(state, val) {
			let findResult = state.cart.find(item => item.goods_id === val.goods_id)
			findResult ? findResult.goods_state = val.goods_state : false
			this.commit('store_cart/saveToStorage')
		},
		
		// 修改 goods_count
		updateCount(state, val) {
			let findResult = state.cart.find(item => item.goods_id === val.goods_id)
			findResult ? findResult.goods_count = val.goods_count : false
			this.commit('store_cart/saveToStorage')
		},
		
		// 全选 / 撤销全选 事件
		updateAllState(state, val) {
			for (let i in state.cart) {
				state.cart[i].goods_state = val.state
			}
			
			// 等价于
			// state.cart.forEach(x => x.goods_state = val.state)
			
			this.commit('store_cart/saveToStorage')
		},
		
		// 删除 goods
		deleteGoods(state, val) {
			// let findResult = state.cart.find(item => item.goods_id === val.goods_id)
			// findResult ? findResult.goods_count = val.goods_count : false
			state.cart = state.cart.filter(x => x.goods_id !== val)
			this.commit('store_cart/saveToStorage')
		},
		
		// 改变 checkAll 状态
		changeCheckState(state, val) {
			state.checkAll = val
		},
		
		// 判断全选状态
		isCheckAll(state) {
			let checkCount = state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
			checkCount === state.cart.length ? state.checkAll = true : state.checkAll = false
			console.log('state.checkAll : ', state.checkAll)
		}
	},
	
	getters: {
		// 获取商品总数量
		total(state) {
			let count = 0
			state.cart.forEach(item => count += item.goods_count)
			return count
		},
		
		// 购物车勾选商品的总数量
		checkCount(state) {
			// state.cart.filter(x => x.goods_state) 表示 过滤 已勾选的商品
			// reduce((total, item) => total += item.goods_count, 0) 表示累加已勾商品的数量
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
		},
		
		// 获取所有商品的价格
		getPrice(state) {
			return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_price * item.goods_count, 0)
		}
	}
}